package com.liu.hadoop.clickStreamETL.mapreduce;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;

/**
 * @Description: 排序类，通过receiveTime(接收数据时间)来对时间进行排序。
 * @author 刘章程
 */
public class SortComparator extends WritableComparator {

	protected SortComparator() {
		// ???
		super(Text.class, true);
	}

	@Override
	public int compare(@SuppressWarnings("rawtypes") WritableComparable w1,
			@SuppressWarnings("rawtypes") WritableComparable w2) {

		String[] comp1 = w1.toString().split("&");
		String[] comp2 = w2.toString().split("&");

		int result = 1;

		if (comp1 != null && comp2 != null) {
			// 先比较sessionid是否一致
			result = comp1[0].compareTo(comp2[0]);

			// sessionId相同和receiveTime
			if (result == 0 && comp1.length > 1 && comp2.length > 1) {
				
				long receiveTime1 = 0;
				long receiveTime2 = 0;

				try {
					receiveTime1 = Long.parseLong(comp1[1]);
					receiveTime2 = Long.parseLong(comp2[1]);
					long res = receiveTime1 - receiveTime2;
	
					if (res == 0) {
						// receiveTime
						result = 0;
					} else {
						// receiveTime
						result = res > 0 ? 1 : -1;
					}
				} catch (Exception e) {
					return result;
				}

			}

		}

		return result;
	}

}
